<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/10/26
// | DESC: 
// +----------------------------------------------------------------------

declare (strict_types=1);


namespace My\core\frame;

use Illuminate\Database\Capsule\Manager;

/**
 * 标注后 调用方法会有提示
 * @mixin \Illuminate\Database\Capsule\Manager
 */
class DbManager
{
    /**
     * @var \Illuminate\Database\Capsule\Manager
     */
    private $manager;

    //默认链接
    private $defaultConnection;

    //当前连接名称
    private $currentConnection;



    /**
     * @param mixed $currentConnection
     */
    public function setCurrentConnection($currentConnection): void
    {
        $this->currentConnection = $currentConnection;
    }
    //临时链接
    private $isTemp = false;

    public function __construct()
    {
        global $GLOBAL_CONFIGS;     //使用全局常量
        $configs = $GLOBAL_CONFIGS;
        if(empty($configs['db'])){
            throw new \RuntimeException('未提供数据库配置');
        }

        $this->manager = new Manager();
        //注册链接
        foreach ($configs['db'] as $name=>$config){
            $this->manager->addConnection($config, $name);
        }

        // 设置默认连接,不穿connection name时使用
        if (isset($configs['db']['default'])){
            $this->defaultConnection = 'default';
        }else{
            //设置第一个配置为当前
            $this->defaultConnection = array_key_first($configs['db']);
        }

        // 设置默认连接的全局访问
        $this->manager->setAsGlobal();
        $this->manager->bootEloquent();
    }



    /**
     * 切换数据库连接
     * @param string $name
     * @return $this
     */
    public function connection(string $name)
    {
        if(!isset($this->connections[$name])){
            throw new \InvalidArgumentException("{$name}的数据库连接不存在");
        }
        $this->currentConnection = $name;
        $this->isTemp = true;
        return $this;
    }

    public function __call($methodName, $args)
    {
        $res = $this->manager::connection($this->currentConnection)->$methodName(...$args);
        if($this->isTemp){
            //将链接重置为默认链接
            $this->currentConnection = $this->defaultConnection;
        }
        return $res;
    }
}